<?php

namespace app\shop\controller;

use think\Request;
use think\Exception;
use app\shop\model\User as UserModel;

class User extends \ShopController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $userModel = new UserModel();

        try {
            $data = $userModel->where([
                'status' => 1,
            ])->order('user_id')
                ->field('user_id,user_name,mobile,email,qq,create_at')
                ->select();

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $userModel = new UserModel();

        $data = $request->post();

        /* @var $validate \ShopValidate */
        $validate = \think\Loader::validate('User');
        if ( !$validate->scene('save')->check($data) ) {
            return $validate->getError();
        }

        try {
            $data['salt'] = $userModel->generateSalt();
            $data['password'] = md5($data['password'] . $data['salt']);

            $result = $userModel->data($data)->allowField(true)->save();

            if (! $result) {
                $this->serverErrorTerminate('资源新增失败');
            }
            unset($userModel->password);
            unset($userModel->salt);

            $this->successTerminate($userModel);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $userModel = new UserModel();

        try {
            $data = $userModel->get($id);
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $userModel = new UserModel();
        $data = $request->post();

        $pk = $userModel->getPk();
        if ( isset($data[$pk]) ) unset($data[$pk]);

        try {
            $result = $userModel->allowField(true)->save($data, [
                $pk => $id,
            ]);
            if (! $result) $this->serverErrorTerminate('更新资源失败');
            $this->successTerminate($userModel);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $userModel = new UserModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }



    /**
     * 登录
     */
    public function login($username, $password, $platform = '')
    {
        try {
            $userModel = new UserModel();
            $user = $userModel->field('user_id,user_name,mobile,email,qq,password,salt,status')
                ->where('user_name', $username)
                ->find();
            empty($user) && \exception('用户名不存在');

            $user->status === 0 && \exception('用户不可用');

            $passwordUser = md5($password . $user->salt);
            $passwordUser === $user->password || \exception('密码错误');

            // 登录成功
            // 生成token & 更新最后登录时间
            $lastLoginKey = 'last_login';
            $tokenKey = 'token';

            if (in_array($platform, config('platform'))) {
                $lastLoginKey .= "_{$platform}";
                $tokenKey .= "_{$platform}";
            }

            $data = [
                $lastLoginKey => time(),
                $tokenKey => $this->generateToken(),
            ];
            $userModel->save($data, [
                'user_id' => $user->user_id,
            ]);

            $user->setAttr('token', $data[$tokenKey]);

            unset($user->password);
            unset($user->salt);

            $this->successTerminate($user);

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }



    protected function noVerifyToken()
    {
        return ['login', 'save'];
    }
}
